import { CheckOutlined, CloseOutlined, ExclamationCircleOutlined, PlusOutlined } from '@ant-design/icons';
import type { ActionType, ColumnsState, ProColumns } from '@ant-design/pro-components';
import {
  FooterToolbar,
  ModalForm,
  PageContainer,
  ProDescriptions,
  ProFormText,
  ProFormTextArea,
  ProTable,
} from '@ant-design/pro-components';
import { FormattedMessage, useIntl,useModel} from '@umijs/max';
import { Button, Drawer, Form, Input, message, Modal } from 'antd';
import React, { useEffect, useRef, useState } from 'react';
import AddForm from './components/AddForm';
import { approvePayment, pagedPayment, discardPayment } from '@/services/payment/payment_api';
import { get_map } from '@/services/system_api';
import { PaymentPageRespVO } from './types';
import TextArea from 'antd/lib/input/TextArea';
import { formatToLocalTime, toUTC } from '@/utils/time';

const PaymentList: React.FC = () => {
  const [createModalOpen, handleModalOpen] = useState<boolean>(false);
  const [form] = Form.useForm();
  const { currentUser } = useModel('@@initialState').initialState || {};
  const [admin, setAdmin] = useState(currentUser?.isAdmin);
  const actionRef = useRef<ActionType>();
  const [currentRecord, setCurrentRecord] = useState<PaymentPageRespVO | null>(null);
  const [approveVisible, setApproveVisible] = useState(false);
  const [updateModalOpen, handleUpdateModalOpen] = useState<boolean>(false);
  const intl = useIntl();

  const [enums, setEnums] = useState<{
    pmCode: Record<string, any>;
    status: Record<string, any>;
  }>({ pmCode: {}, status: {} });

  useEffect(() => {
    const fetchEnums = async () => {
      try {
        const [pmCodeRes, statusRes] = await Promise.all([
          get_map("brokerage_withdraw_type"),
          get_map("elm_pay_status")
        ]);

        setEnums({
          pmCode: pmCodeRes.data.reduce((acc, { label, value }) => {
            acc[value] = { text: label };
            return acc;
          }, {}),
          status: statusRes.data.reduce((acc, { label, value }) => {
            acc[value] = { text: label };
            return acc;
          }, {})
        });
      } catch (error) {
        console.error('Failed to load enums:', error);
        message.error(intl.formatMessage({ id: 'pages.payment.messages.enumError' }));
      }
    };

    fetchEnums();
  }, []);

  const handleApprove = async (values: { operatorDesc: string, status: number }) => {
    try {
      const response = await approvePayment({
        id: currentRecord?.id,
        ...values
      });
      if (response.code != 0) {
        message.error(response.msg || intl.formatMessage({ id: "request.error.create" }));
        return;
      }    
      setApproveVisible(false);
      actionRef.current?.reload();
      message.success(intl.formatMessage({ id: 'pages.payment.messages.approveSuccess' }));
    } catch (error) {
      message.error(intl.formatMessage({ id: 'pages.payment.messages.approveError' }));
    }
  };

  const handleInvalid = async (record: PaymentPageRespVO) => {
    Modal.confirm({
      title: intl.formatMessage({ id: 'pages.payment.confirm.invalid.title' }),
      icon: <ExclamationCircleOutlined />,
      content: intl.formatMessage(
        { id: 'pages.payment.confirm.invalid.content' },
        { transactionNo: record.transactionNo }
      ),
      okText: intl.formatMessage({ id: 'pages.payment.actions.confirmInvalid' }),
      cancelText: intl.formatMessage({ id: 'pages.button.cancel' }),
      okButtonProps: { danger: true },
      async onOk() {
        try {
          await discardPayment({
            id: record.id,
            status: 3,
            operatorDesc: intl.formatMessage({ id: 'pages.payment.status.invalid' })
          });
          message.success(intl.formatMessage(
            { id: 'pages.payment.messages.invalidSuccess' },
            { transactionNo: record.transactionNo }
          ));
          actionRef.current?.reload();
        } catch (error) {
          message.error(intl.formatMessage(
            { id: 'pages.payment.messages.invalidError' },
            { error: error.message }
          ));
        }
      }
    });
  };

  const showApproveModal = (record: PaymentPageRespVO) => {
    setCurrentRecord(record);
    setApproveVisible(true);
    form.resetFields();
  };

  const columns: ProColumns<PaymentPageRespVO>[] = [
    {
      title: intl.formatMessage({ id: 'pages.payment.columns.customerCode' }),
      search: admin,
      dataIndex: 'customerCode',
    },
    {
      title: intl.formatMessage({ id: 'pages.payment.columns.customerName' }),
      search: false,
      dataIndex: 'customerName',
    },
    {
      title: intl.formatMessage({ id: 'pages.payment.columns.transactionNo' }),
      dataIndex: 'transactionNo',
    },
    {
      title: intl.formatMessage({ id: 'pages.payment.columns.amount' }),
      dataIndex: 'amount',
      hideInSearch: true,
    },
    {
      title: intl.formatMessage({ id: 'pages.payment.columns.pmCode' }),
      dataIndex: 'pmCode',
      hideInForm: true,
      valueEnum: enums.pmCode,
    },
    {
      title: intl.formatMessage({ id: 'pages.payment.columns.realAmount' }),
      dataIndex: 'realAmount',
      sorter: true,
      hideInForm: true,
      hideInSearch: true,
    },
    {
      title: intl.formatMessage({ id: 'pages.payment.columns.note' }),
      dataIndex: 'note',
      sorter: true,
      hideInForm: true,
      hideInSearch: true,
    },
    {
      title: intl.formatMessage({ id: 'pages.payment.columns.status' }),
      dataIndex: 'status',
      valueEnum: enums.status,
    },
    {
      title: intl.formatMessage({ id: 'pages.payment.columns.note' }),
      dataIndex: 'note',
      hideInSearch: true,
    },
    {
      title: intl.formatMessage({ id: 'pages.createTime' }),
      dataIndex: 'createTime',
      sorter: true,
      valueType: 'dateRange',
      hideInForm: true,
      search: {
        transform: (value) => ({
          startTime: toUTC(value[0]),
          endTime: toUTC(value[1], true)
        })
      },
      render: (_, record) => formatToLocalTime(record.createTime)
    },
    {
      title: intl.formatMessage({ id: 'pages.payment.columns.confirmTime' }),
      dataIndex: 'confirmTime',
      sorter: true,
      hideInForm: true,
      hideInSearch: true,
      render: (_, record) => record.confirmTime ? formatToLocalTime(record.confirmTime) : "-"
    },
    {
      title: intl.formatMessage({ id: 'pages.payment.columns.operatorDesc' }),
      dataIndex: 'operatorDesc',
      hideInSearch: true,
    },
    {
      title: intl.formatMessage({ id: 'pages.operating' }),
      dataIndex: 'option',
      valueType: 'option',
      width: 120,
      fixed: 'right',
      render: (_, record) => (
        <div>
          {record.status === 0 && (
            <a key="edit" onClick={() => {
              setCurrentRecord(record);
              handleUpdateModalOpen(true);
            }}>
              <FormattedMessage id="pages.edit" />
            </a>
          )}
          {admin && record.status === 0 && (
            <a key='approval' style={{ marginLeft: 10 }} onClick={() => showApproveModal(record)}>
              <FormattedMessage id="pages.payment.actions.approve" />
            </a>
          )}
          {record.status === 0 && (
            <a key='invalid' style={{ marginLeft: 10 }} onClick={() => handleInvalid(record)}>
              <FormattedMessage id="pages.payment.actions.invalid" />
            </a>
          )}
        </div>
      ),
    },
  ];

  const [columnsStateMap, setColumnsStateMap] = useState<Record<string, ColumnsState>>({
    updateTime: { show: false },
  });

  return (
    <PageContainer header={{ title: false }}>
      <ProTable<PaymentPageRespVO>
        headerTitle={intl.formatMessage({ id: "pages.searchTable.title" })}
        actionRef={actionRef}
        rowKey="key"
        search={{ labelWidth: 120 }}
        toolBarRender={() => [
          <Button
            type="primary"
            key="primary"
            onClick={() => handleModalOpen(true)}
          >
            <PlusOutlined /> <FormattedMessage id="pages.payment.new" />
          </Button>
        ]}
        request={pagedPayment}
        columns={columns}
        columnsState={{
          value: columnsStateMap,
          onChange: setColumnsStateMap,
        }}
        scroll={{ x: 'max-content' }}
      />

      <Modal
        title={intl.formatMessage({ id: 'pages.payment.modal.approvalTitle' })}
        visible={approveVisible}
        onCancel={() => setApproveVisible(false)}
        footer={[
          <Button key="cancel" onClick={() => setApproveVisible(false)}>
            <FormattedMessage id="pages.button.cancel" />
          </Button>,
          <Button
            key="reject"
            danger
            onClick={() => {
              form.validateFields().then(values => {
                handleApprove({ ...values, status: 2 });
              });
            }}
          >
            <CloseOutlined /> <FormattedMessage id="pages.payment.actions.reject" />
          </Button>,
          <Button
            key="approve"
            type="primary"
            onClick={() => {
              form.validateFields().then(values => {
                handleApprove({ ...values, status: 1 });
              });
            }}
          >
            <CheckOutlined /> <FormattedMessage id="pages.payment.actions.approve" />
          </Button>,
        ]}
      >
        <Form form={form} layout="vertical">
          <Form.Item
            name="operatorDesc"
            label={intl.formatMessage({ id: 'pages.payment.modal.approvalComments' })}
            rules={[{
              required: true,
              message: intl.formatMessage({ id: 'pages.payment.modal.approvalCommentsRequired' })
            }]}
          >
            <TextArea
              rows={4}
              placeholder={intl.formatMessage({ id: 'pages.payment.modal.approvalCommentsPlaceholder' })}
            />
          </Form.Item>
        </Form>
      </Modal>

      <AddForm
        visible={createModalOpen}
        onCancel={() => handleModalOpen(false)}
        onSuccess={() => {
          handleModalOpen(false);
          setCurrentRecord(null);
          actionRef.current?.reload();
        }}
      />

      {currentRecord && (
        <AddForm
          values={currentRecord}
          visible={updateModalOpen}
          onCancel={() => handleUpdateModalOpen(false)}
          onSuccess={() => {
            handleUpdateModalOpen(false);
            setCurrentRecord(null);
            actionRef.current?.reload();
          }}
        />
      )}
    </PageContainer>
  );
};

export default PaymentList;